#!/usr/bin/env python
# -*- coding: utf-8 -*-

from typing import Any

from cta.interface.action.filter.abstract_filter_action import AbstractFilterAction
from web.constants.datetime_format import DatetimeFormat
from web.domain.responsibility_chain_dto import ResponsibilityChainDto
from web.manager.log_manager import LogManager
from web.models.quant2_commodity_future_filter import Quant2CommodityFutureFilter
from web.util.datetime_util import DatetimeUtil

Logger = LogManager.get_logger(__name__)

class NormalizationVariance123FilterAction(AbstractFilterAction):
    """
    归一化normalization_variance120列，公式：UPDATE t SET res = (a-SELECT min(a) FROM t)/(SELECT max(a)-min(a) FROM t)
    """

    def exec(self, responsibility_chain_dto: ResponsibilityChainDto = None):

        transaction_date: str = DatetimeUtil.datetime_to_str(responsibility_chain_dto, DatetimeFormat.Date_Format)

        Logger.info("将120日方差归一化，日期[%s]", transaction_date)

        # 查询quant2_c_f_filter表全部记录
        quant2_commodity_future_filter_list: list[Quant2CommodityFutureFilter] = self.quant2_commodity_future_filter_dao.find_all()
        if quant2_commodity_future_filter_list is not None and len(quant2_commodity_future_filter_list) > 0:
            for quant2_commodity_future_filter in quant2_commodity_future_filter_list:
                # 根据code，查询当前的variance120、最大的variance120和最小的variance120
                current_variance120, max_variance120, min_variance120 = self.quant2_commodity_future_filter_dao.find_current_and_max_and_min_variance20(quant2_commodity_future_filter.code, transaction_date)

                # 如果没有120日方差、最大的120日方差或最小的120日方差，则删除这条记录
                if current_variance120 is None or max_variance120 is None or min_variance120 is None:
                    Logger.warning("期货[%s]在日期[%s]没有120日方差、最大的120日方差或最小的120日方差，因此删除这条记录", quant2_commodity_future_filter.code, transaction_date)

                    self.quant2_commodity_future_filter_dao.delete(quant2_commodity_future_filter)

                    continue

                # 归一化
                normalization_variance120: float = (float(current_variance120) - float(min_variance120))/(float(max_variance120) - float(min_variance120))

                # 更新
                quant2_commodity_future_filter.normalization_variance120 = normalization_variance120
                self.quant2_commodity_future_filter_dao.update(quant2_commodity_future_filter)
        else:
            Logger.warning("表quant2_c_f_filter为空")

        super().next(responsibility_chain_dto)